/*******************************************************************************
 * Copyright 2012 Francesco Foresti
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package it.fflabs.dynscript.client.handler;

import it.fflabs.dynscript.client.JsClient;
import it.fflabs.dynscript.client.validation.IJsValidator;
import it.fflabs.dynscript.client.validation.exception.JsValidationException;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * <b>gwt-jsClient : JsHandler</b><br>
 * <hr>
 * Comment: This class is used to handle the response of the request issued by
 * {@link JsClient} <br>
 * <hr>
 * 12/dic/2011<br>
 * 
 * @author frafore
 * 
 */
public class JsHandler {

	private final IJsCallBack _callback;
	private final IJsValidator _validator;

	public JsHandler(IJsCallBack callback, IJsValidator validator) {
		_callback = callback;
		_validator = validator;
	}

	/**
	 * Handle the response to a request sent to a remote server. First
	 * of all the object is validated against the provided {@link IJsValidator}.
	 * If validation succeeds, the {@link IJsCallback} is executed, otherwise
	 * an {@link JsValidationException} is thrown.
	 */
	public void handleResponse(JavaScriptObject jso) throws JsValidationException {
		try {
			_validator.validate(jso);
		} catch (Exception e) {
			throw new JsValidationException(e.getMessage());
		}
		_callback.onSuccess(jso);
	}
	
	/**
	 * Handle the case of a response timeout.
	 */
	public void handleTimeout() {
		_callback.onTimeout();
	}
}
